package com.nba.servlet;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.nba.bean.Player;
import com.nba.bean.Team;
import com.nba.dao.PartitionDao;
import com.nba.dao.TypeDao;
import com.nba.dao.UnionDao;
import com.nba.dao.impl.PartitionDaoImpl;
import com.nba.dao.impl.TypeDaoImpl;
import com.nba.dao.impl.UnionDaoImpl;
import com.nba.service.PlayerService;
import com.nba.service.TeamService;
import com.nba.service.impl.PlayerServiceImpl;
import com.nba.service.impl.TeamServiceImpl;

@WebServlet("/playerServlet.do")
public class PlayerServlet extends HttpServlet{
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}


	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String opt = request.getParameter("opt");
		switch(opt) {
			case "0":
				delete(request,response);
				break;
			case "1":
				add(request,response);
				break;
			case "2":
				deleteAll(request,response);
				break;
			case "3":
				update(request,response);
				break;
			case "4":
				break;
		}
	}
	
	public void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PlayerService ps = new PlayerServiceImpl();
		int playerId = Integer.parseInt(request.getParameter("playerId"));
		ps.deletePlayer(playerId);
		response.sendRedirect("SearchServlet.do");
	}
	public void deleteAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PlayerService ps = new PlayerServiceImpl();
		String ids = request.getParameter("ids");
		if(ids!=null) {
			String[] idArray = ids.split("_");
			for (int i = 0; i < idArray.length; i++) {
				ps.deletePlayer(Integer.parseInt(idArray[i]));			}
		}
	}
	public void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PlayerService ps = new PlayerServiceImpl();
		int playerId = Integer.parseInt(request.getParameter("playerId"));
		FileItemFactory itemFactory = new DiskFileItemFactory();//鍒涘缓涓�涓笂浼犳枃浠跺伐鍘傜被
		ServletFileUpload upload = new ServletFileUpload(itemFactory); //鍒涘缓涓�涓� 鏂囦欢涓婁紶 鏍稿績瀵硅薄
		upload.setHeaderEncoding("UTF-8"); // 璁剧疆 璇锋眰澶寸殑缂栫爜鏍煎紡涓� UTF-8 鐩殑鏄繚璇佸悗缁� 琛ㄥ崟涓殑涓枃鑳藉姝ｅ父鑾峰彇
		//upload.setFileSizeMax(1024*1024); // 璁剧疆 涓婁紶鐨勬椂鍊� 鍗曚釜鏂囦欢鏈�澶уぇ灏� 鍗曚綅 瀛楄妭
		//upload.setSizeMax(1024*1024); // 璁剧疆 涓�涓〃鍗曚腑 鎬荤殑涓婁紶鏂囦欢澶у皬 鍗曚綅 瀛�
		if(upload.isMultipartContent(request)) { //鍒ゆ柇 杩欎釜琛ㄥ崟鏄笉鏄竴涓� 鏂囦欢涓婁紶琛ㄥ崟 锛堝垽鏂〃鍗曢噷鏈夋病鏈� enctype="multipart/form-data"锛�
			try {
				String playerName = null;
				String englishName = null;
				int teamId = 0;
				String playerPosition = null; 
				double playerHeight = 0;
				double playerWeight = 0;
				int playerNum = 0;
				String playerNation = null; 
				Date playerDate = null; 
				String playerBefore = null; 
				int playerDraft = 0;
				int playerExp = 0; //鐢ㄤ簬鎺ユ敹 鐢ㄦ埛鍙戣繃鏉ョ殑璇锋眰褰撲腑 鏂囨湰鍙傛暟
				int typeId = 0;
				String playerTitl = null;
				String playerBody = null;
				List<FileItem> items = upload.parseRequest(request); // 鏍稿績瀵硅薄鎶� 璇锋眰涓殑 鍙傛暟(鏂囨湰銆佹枃浠�) 杞崲鎴愪竴涓� FileItem闆嗗悎
				for(FileItem item : items) {//閬嶅巻鎵�鏈� 缁勪欢
					
					if(item.isFormField()) { //鍒ゆ柇鍙栧嚭鐨勭粍浠舵槸鍚︽槸鏂囨湰
//						System.out.println(item.getFieldName());//鑾峰彇缁勪欢鍦ㄨ〃鍗曚腑name灞炴�х殑鍊�
//						System.out.println(item.getName());//鏂囨湰鏃犳晥
//						System.out.println(item.getContentType());//鏂囨湰鏃犳晥
//						System.out.println(item.getString("UTF-8"));//鑾峰彇缁勪欢鐨勫�硷紙鍙敤浜庢枃鏈級
						if("playerName".equals(item.getFieldName())) {
							playerName = item.getString("UTF-8");
						}
						if("englishName".equals(item.getFieldName())) {
							englishName = item.getString("UTF-8");
						}
						if("playerPosition".equals(item.getFieldName())) {
							playerPosition = item.getString("UTF-8");
						}
						if("playerNation".equals(item.getFieldName())) {
							playerNation = item.getString("UTF-8");
						}
						if("playerBefore".equals(item.getFieldName())) {
							playerBefore = item.getString("UTF-8");
						}
						if("playerHeight".equals(item.getFieldName())) {
							playerHeight = Double.parseDouble(item.getString("UTF-8"));
						}
						if("playerWeight".equals(item.getFieldName())) {
							playerWeight = Double.parseDouble(item.getString("UTF-8"));
						}
						if("playerNum".equals(item.getFieldName())) {
							playerNum = Integer.parseInt(item.getString("UTF-8"));
						}
						if("playerExp".equals(item.getFieldName())) {
							playerExp = Integer.parseInt(item.getString("UTF-8"));
						}
						if("teamName".equals(item.getFieldName())) {
							String teamName = item.getString("UTF-8");
							TeamService ts = new TeamServiceImpl();
							teamId = ts.selectTeamByName(teamName).getTeamId();
						}
						if("typeName".equals(item.getFieldName())) {
							typeId = Integer.parseInt(item.getString("UTF-8"));
						}
						if("playerDate".equals(item.getFieldName())) {
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
							String str = item.getString("UTF-8").replace("T"," ");
							playerDate = format.parse(str);
						}
						if("playerDraft".equals(item.getFieldName())) {
							playerDraft = Integer.parseInt(item.getString("UTF-8"));
						}
						
					}else {//涓嶆槸缁勪欢锛屾槸涓�涓枃浠�
						
//						System.out.println(item.getName());//鑾峰彇鐢ㄦ埛涓婁紶鏂囦欢鐨� 鍘熷鏂囦欢鍚嶅瓧
//						System.out.println(item.getContentType());//鑾峰彇 鐢ㄦ埛涓婁紶鏂囦欢鐨勭被鍨� contentType
//						System.out.println(item.getString("UTF-8"));//鑾峰彇缁勪欢鐨勫�硷紙鍙敤浜庢枃鏈級
//						System.out.println(item.getSize()) ;鑾峰彇 涓婁紶鏂囦欢鐨勫ぇ灏�
//						InputStream ins = item.getInputStream();//鑾峰彇 涓婁紶鏂囦欢璇诲彇鐨勮緭鍏ユ祦锛岀敤浜庤鐢ㄦ埛涓婁紶鐨勬枃浠讹紝鎵嬪姩澶嶅埗
//						String realPath = req.getServletContext().getRealPath("userImg");// 鑾峰彇椤圭洰璺緞涓� 鏌愪釜鏂囦欢澶圭殑 鐪熷疄璺緞銆佹妸鏂囦欢瀛樺湪 椤圭洰璺緞涓�
						//甯屾湜 鎶婄▼搴� 鍜� 涓婁紶鐨勬枃浠跺垎寮�锛屾妸鏂囦欢 椤圭洰璺緞涔嬪(涓嶆斁鍦╰omcat閲�)
						String realPath = "C://nba/images/player";
						File folder = new File(realPath);//鍥剧墖淇濆瓨鍦� 鏈嶅姟鍣ㄧ殑鏌愪釜鐪熷疄鍦板潃(涓嶆斁鍦ㄩ」鐩矾寰勪笅)
						if(!folder.exists()) {
							folder.mkdirs();
						}
						if("playerTitl".equals(item.getFieldName())) {
							playerTitl = System.currentTimeMillis()+item.getName().substring(item.getName().lastIndexOf("."));
							File desFile = new File(realPath,playerTitl);
							item.write(desFile);
						}
						if("playerBody".equals(item.getFieldName())) {
							playerBody = System.currentTimeMillis()+item.getName().substring(item.getName().lastIndexOf("."));
							File desFile = new File(realPath,playerBody);
							item.write(desFile);
						}
					}
//					
				}
				
				//璁剧疆 鏁版嵁搴撻噷瀛樺偍鐨� 涔︾殑璺緞
				String playerTitlPath = "/nba/images/player/"+playerTitl;
				String playerBodyPath = "/nba/images/player/"+playerBody;
				Player player = new Player(playerId, playerName, englishName, playerTitlPath, playerBodyPath, teamId, playerPosition, playerHeight, playerWeight, playerNum, playerExp, playerNation, playerDate, playerBefore, playerDraft, typeId);
				ps.updatePlayer(player);
				response.sendRedirect("SearchServlet.do");
			} catch (FileUploadException e) {

				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("涓嶆槸鏂囦欢涓婁紶琛ㄥ崟");
		}

	}
	public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		PlayerService ps = new PlayerServiceImpl();
		FileItemFactory itemFactory = new DiskFileItemFactory();//鍒涘缓涓�涓笂浼犳枃浠跺伐鍘傜被
		ServletFileUpload upload = new ServletFileUpload(itemFactory); //鍒涘缓涓�涓� 鏂囦欢涓婁紶 鏍稿績瀵硅薄
		upload.setHeaderEncoding("UTF-8"); // 璁剧疆 璇锋眰澶寸殑缂栫爜鏍煎紡涓� UTF-8 鐩殑鏄繚璇佸悗缁� 琛ㄥ崟涓殑涓枃鑳藉姝ｅ父鑾峰彇
		//upload.setFileSizeMax(1024*1024); // 璁剧疆 涓婁紶鐨勬椂鍊� 鍗曚釜鏂囦欢鏈�澶уぇ灏� 鍗曚綅 瀛楄妭
		//upload.setSizeMax(1024*1024); // 璁剧疆 涓�涓〃鍗曚腑 鎬荤殑涓婁紶鏂囦欢澶у皬 鍗曚綅 瀛�
		if(upload.isMultipartContent(req)) { //鍒ゆ柇 杩欎釜琛ㄥ崟鏄笉鏄竴涓� 鏂囦欢涓婁紶琛ㄥ崟 锛堝垽鏂〃鍗曢噷鏈夋病鏈� enctype="multipart/form-data"锛�
			try {
				String playerName = null;
				String englishName = null;
				int teamId = 0;
				String playerPosition = null; 
				double playerHeight = 0;
				double playerWeight = 0;
				int playerNum = 0;
				String playerNation = null; 
				Date playerDate = null; 
				String playerBefore = null; 
				int playerDraft = 0;
				int playerExp = 0; //鐢ㄤ簬鎺ユ敹 鐢ㄦ埛鍙戣繃鏉ョ殑璇锋眰褰撲腑 鏂囨湰鍙傛暟
				int typeId = 0;
				String playerTitl = null;
				String playerBody = null;
				List<FileItem> items = upload.parseRequest(req); // 鏍稿績瀵硅薄鎶� 璇锋眰涓殑 鍙傛暟(鏂囨湰銆佹枃浠�) 杞崲鎴愪竴涓� FileItem闆嗗悎
				for(FileItem item : items) {//閬嶅巻鎵�鏈� 缁勪欢
					
					if(item.isFormField()) { //鍒ゆ柇鍙栧嚭鐨勭粍浠舵槸鍚︽槸鏂囨湰
//						System.out.println(item.getFieldName());//鑾峰彇缁勪欢鍦ㄨ〃鍗曚腑name灞炴�х殑鍊�
//						System.out.println(item.getName());//鏂囨湰鏃犳晥
//						System.out.println(item.getContentType());//鏂囨湰鏃犳晥
//						System.out.println(item.getString("UTF-8"));//鑾峰彇缁勪欢鐨勫�硷紙鍙敤浜庢枃鏈級
						if("addplayerName".equals(item.getFieldName())) {
							playerName = item.getString("UTF-8");
						}
						if("addplayerEName".equals(item.getFieldName())) {
							englishName = item.getString("UTF-8");
						}
						if("addPosition".equals(item.getFieldName())) {
							playerPosition = item.getString("UTF-8");
						}
						if("addNation".equals(item.getFieldName())) {
							playerNation = item.getString("UTF-8");
						}
						if("addBefore".equals(item.getFieldName())) {
							playerBefore = item.getString("UTF-8");
						}
						if("addHeight".equals(item.getFieldName())) {
							playerHeight = Double.parseDouble(item.getString("UTF-8"));
						}
						if("addWeight".equals(item.getFieldName())) {
							playerWeight = Double.parseDouble(item.getString("UTF-8"));
						}
						if("addplayerNum".equals(item.getFieldName())) {
							playerNum = Integer.parseInt(item.getString("UTF-8"));
						}
						if("addExp".equals(item.getFieldName())) {
							playerExp = Integer.parseInt(item.getString("UTF-8"));
						}
						if("addteamName".equals(item.getFieldName())) {
							String teamName = item.getString("UTF-8");
							TeamService ts = new TeamServiceImpl();
							teamId = ts.selectTeamByName(teamName).getTeamId();
						}
						if("ptype".equals(item.getFieldName())) {
							typeId = Integer.parseInt(item.getString("UTF-8"));
						}
						if("addplayerDate".equals(item.getFieldName())) {
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
							String str = item.getString("UTF-8").replace("T"," ");
							playerDate = format.parse(str);
							System.out.println(playerDate);
						}
						if("addDraft".equals(item.getFieldName())) {
							playerDraft = Integer.parseInt(item.getString("UTF-8"));
						}
						
					}else {//涓嶆槸缁勪欢锛屾槸涓�涓枃浠�
						
//						System.out.println(item.getName());//鑾峰彇鐢ㄦ埛涓婁紶鏂囦欢鐨� 鍘熷鏂囦欢鍚嶅瓧
//						System.out.println(item.getContentType());//鑾峰彇 鐢ㄦ埛涓婁紶鏂囦欢鐨勭被鍨� contentType
//						System.out.println(item.getString("UTF-8"));//鑾峰彇缁勪欢鐨勫�硷紙鍙敤浜庢枃鏈級
//						System.out.println(item.getSize()) ;鑾峰彇 涓婁紶鏂囦欢鐨勫ぇ灏�
//						InputStream ins = item.getInputStream();//鑾峰彇 涓婁紶鏂囦欢璇诲彇鐨勮緭鍏ユ祦锛岀敤浜庤鐢ㄦ埛涓婁紶鐨勬枃浠讹紝鎵嬪姩澶嶅埗
//						String realPath = req.getServletContext().getRealPath("userImg");// 鑾峰彇椤圭洰璺緞涓� 鏌愪釜鏂囦欢澶圭殑 鐪熷疄璺緞銆佹妸鏂囦欢瀛樺湪 椤圭洰璺緞涓�
						//甯屾湜 鎶婄▼搴� 鍜� 涓婁紶鐨勬枃浠跺垎寮�锛屾妸鏂囦欢 椤圭洰璺緞涔嬪(涓嶆斁鍦╰omcat閲�)
						String realPath = "C://nba/images/player";
						File folder = new File(realPath);//鍥剧墖淇濆瓨鍦� 鏈嶅姟鍣ㄧ殑鏌愪釜鐪熷疄鍦板潃(涓嶆斁鍦ㄩ」鐩矾寰勪笅)
						if(!folder.exists()) {
							folder.mkdirs();
						}
						if("addplayerTitle".equals(item.getFieldName())) {
							playerTitl = System.currentTimeMillis()+item.getName().substring(item.getName().lastIndexOf("."));
							File desFile = new File(realPath,playerTitl);
							item.write(desFile);
						}
						if("addplayerBody".equals(item.getFieldName())) {
							playerBody = System.currentTimeMillis()+item.getName().substring(item.getName().lastIndexOf("."));
							File desFile = new File(realPath,playerBody);
							item.write(desFile);
						}
					}
//					
				}
				
				//璁剧疆 鏁版嵁搴撻噷瀛樺偍鐨� 涔︾殑璺緞
				String playerTitlPath = "/nba/images/player/"+playerTitl;
				String playerBodyPath = "/nba/images/player/"+playerBody;
				Player player = new Player(playerName, englishName, playerTitlPath, playerBodyPath, teamId, playerPosition, playerHeight, playerWeight, playerNum, playerExp, playerNation, playerDate, playerBefore, playerDraft, typeId);
				ps.addPlayer(player);
				resp.sendRedirect("SearchServlet.do");
			} catch (FileUploadException e) {

				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			System.out.println("涓嶆槸鏂囦欢涓婁紶琛ㄥ崟");
		}
	}
}

